package com.cgmnx.admin.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;


public class SpringAppContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContextHolder;

    private static void setAppContext(ApplicationContext applicationContext) {
        applicationContextHolder = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz, String beanName) {
        return applicationContextHolder.getBean(beanName, clazz);
    }

    public static <T> Map<String, T> getBeanOfType(Class<T> clazz) {
        return applicationContextHolder.getBeansOfType(clazz);
    }

    /**
     * 获取对象实例
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return applicationContextHolder.getBean(beanName);
    }

    /**
     * 获取对象实例
     *
     * @param beanName
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        return applicationContextHolder.getBean(beanName, clazz);
    }

    /**
     * 获取对象实例
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContextHolder.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        setAppContext(applicationContext);
    }
}
